'use client';

import { useEffect, useState } from 'react';
import { Table, Button, Card, Typography, Message, Spin, Badge, Space, Modal } from '@arco-design/web-react';
import { IconPlus } from '@arco-design/web-react/icon';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { bookingApi, roomApi } from '@/services/api';
import { Booking, Room } from '@/types';

const { Title } = Typography;

export default function BookingsPage() {
  const [bookings, setBookings] = useState<(Booking & { roomInfo?: Room })[]>([]);
  const [loading, setLoading] = useState(true);
  const { user, userType, isAuthenticated } = useAuth();
  const router = useRouter();

  // 新增状态用于控制取消预订模态框
  const [cancelModalVisible, setCancelModalVisible] = useState(false);
  const [bookingToCancelId, setBookingToCancelId] = useState<number | null>(null);
  const [cancelLoading, setCancelLoading] = useState(false);

  useEffect(() => {
    fetchBookings();
  }, []);

  const fetchBookings = async () => {
    setLoading(true);
    try {
      console.log('开始获取预订列表...');
      const response = await bookingApi.getByCustomerId();
      console.log('获取预订列表响应:', response);

      if (response.code === 200 && response.data) {
        // 获取每个预订的房间信息
        const bookingsWithRoomInfo = await Promise.all(
          response.data.map(async (booking) => {
            try {
              const roomResponse = await roomApi.getById(booking.roomId);
              if (roomResponse.code === 200 && roomResponse.data) {
                return { ...booking, roomInfo: roomResponse.data };
              }
              return booking;
            } catch (error) {
              console.error('获取房间信息失败:', error);
              return booking;
            }
          })
        );
        setBookings(bookingsWithRoomInfo);
      } else {
        // Message.error(response.message || '获取预订列表失败');
      }
    } catch (error) {
      console.error('获取预订列表错误:', error);
      // Message.error('获取预订列表时发生错误');
    } finally {
      setLoading(false);
    }
  };

  // 修改 handleCancelBooking 函数，只设置状态，不直接弹窗
  const handleCancelBooking = (bookingId: number) => {
    setBookingToCancelId(bookingId);
    setCancelModalVisible(true);
  };

  // 新增函数处理确认取消预订
  const confirmCancelBooking = async () => {
    if (bookingToCancelId === null) return; // Should not happen

    setCancelLoading(true);
    try {
      const response = await bookingApi.cancel(bookingToCancelId);
      if (response.code === 200) {
        Message.success('预订已取消');
        fetchBookings(); // 刷新列表
      } else {
        // Message.error(response.message || '取消预订失败');
      }
    } catch (error) {
      console.error('取消预订错误:', error);
      // Message.error('取消预订时发生错误');
    } finally {
      setCancelLoading(false);
      setCancelModalVisible(false); // 关闭模态框
      setBookingToCancelId(null); // 重置待取消预订ID
    }
  };

  const handleCancelModalClose = () => {
    setCancelModalVisible(false);
    setBookingToCancelId(null);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case '预订中':
        return <Badge status="processing" text="预订中" />;
      case '已入住':
        return <Badge status="success" text="已入住" />;
      case '已退房':
        return <Badge status="default" text="已退房" />;
      case '取消':
        return <Badge status="error" text="已取消" />;
      default:
        return <Badge status="default" text={status} />;
    }
  };

  const columns = [
    {
      title: '房间号',
      dataIndex: 'roomInfo',
      width: 100,
      render: (roomInfo: Room) => roomInfo?.roomNumber || '-',
    },
    {
      title: '预订ID',
      dataIndex: 'bookingId',
      width: 80,
    },
    {
      title: '房间类型',
      dataIndex: 'roomInfo',
      width: 120,
      render: (roomInfo: Room) => roomInfo?.roomType || '-',
    },
    {
      title: '入住日期',
      dataIndex: 'checkInTime',
      width: 120,
      render: (text: string) => new Date(text).toLocaleDateString(),
    },
    {
      title: '退房日期',
      dataIndex: 'checkOutTime',
      width: 120,
      render: (text: string) => new Date(text).toLocaleDateString(),
    },
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      width: 100,
      render: (amount: number) => `¥${amount}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status: string) => getStatusBadge(status),
    },
    {
      title: '操作',
      width: 120,
      render: (_: any, record: Booking) => {
        console.log('预订ID:', record.bookingId, '状态:', record.status);
        return (
          <Space>
            {record.status === '预订中' && (
              <Button
                type="secondary"
                status="danger"
                size="small"
                onClick={() => handleCancelBooking(record.bookingId!)}
              >
                取消
              </Button>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <div className="py-6">
      <Card className="shadow-sm">
        <div className="flex justify-between items-center mb-6">
          <Title heading={3}>我的预订</Title>
          <Button
            type="primary"
            icon={<IconPlus />}
            onClick={() => router.push('/rooms')}
          >
            新预订
          </Button>
        </div>

        {loading ? (
          <div className="flex justify-center py-12">
            <Spin />
          </div>
        ) : (
          <Table
            columns={columns}
            data={bookings}
            loading={loading}
            pagination={{
              pageSize: 10,
              showTotal: true,
            }}
            rowKey="bookingId"
            borderCell={true}
          />
        )}
      </Card>

      {/* 取消预订确认模态框 */}
      <Modal
        title="取消预订"
        visible={cancelModalVisible}
        onOk={confirmCancelBooking}
        onCancel={handleCancelModalClose}
        confirmLoading={cancelLoading}
        okText="确定取消"
        cancelText="取消"
        okButtonProps={{ status: 'danger' }}
      >
        <p>确定要取消这个预订吗？此操作不可撤销。</p>
      </Modal>
    </div>
  );
}